package com.github.uiautomator;

import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.util.Log;

import com.github.uiautomator.compat.WindowManagerWrapper;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class RotationAgent extends Thread {
    private static final String SOCKET = "rotationagent";
    private static final String TAG = RotationAgent.class.getSimpleName();
    private final WindowManagerWrapper wm = new WindowManagerWrapper();

    RotationAgent() {
    }

    private void manageClientConnection(LocalServerSocket serverSocket) {
        while (true) {
            try  {
                LocalSocket socket = serverSocket.accept();
                Log.d(TAG, "client connected");

                PrintWriter writer = new PrintWriter(socket.getOutputStream());
                writer.println(wm.getRotation() * 90);
                writer.flush();
                new Thread(() -> {
                    // 不停的往Client输出当前的Rotation信息
                    try {
                        wm.watchRotation(r -> {
                            writer.println(r * 90);
                            writer.flush();
                        });

                        Scanner in = new Scanner(socket.getInputStream());
                        while (in.hasNextLine()) {
                            Log.v(TAG, in.nextLine());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            Log.v(TAG, "@" + SOCKET + " client connection closed");
                            socket.close();
                        } catch (IOException e) {
                        }
                    }
                }).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        try (LocalServerSocket serverSocket = new LocalServerSocket(SOCKET)) {
            Log.v(TAG, "Listening on localabstract:" + SOCKET);
            manageClientConnection(serverSocket);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
